package vigenere;
import utils.CUtil;


public class Vigenere {
	private String key;
	private String reversekey;
	public Vigenere(String encode)
	{
		key=encode;	
		reversekey=reverse(key);
	}
	
	public String encode(String plain)
	{
		int[] Plain=CUtil.TextToNumbers(plain);
		int[] Key=CUtil.TextToNumbers(key);
		int[] rez=new int[Plain.length];
		
		
		for(int i=0,k=0; i<Plain.length; i++,k=(k+1) % Key.length)
		{
			rez[i]=(Plain[i]+Key[k])%26;
		}
		
		
		return CUtil.NumbersToText(rez);
	}
	
	public String decode(String cipher)
	{
		if(reversekey == null)
			return "";
		int[] Cipher=CUtil.TextToNumbers(cipher);
		int[] Key=CUtil.TextToNumbers(reversekey);
		int[] rez=new int[Cipher.length];
		
		
		for(int i=0,k=0; i<Cipher.length; i++,k=(k+1) % Key.length)
		{
			rez[i]=(Cipher[i]+Key[k])%26;
		}
		
		
		return CUtil.NumbersToText(rez);
	}
	
	
	public static String reverse(String txt)
	{
		int[] arg=CUtil.TextToNumbers(txt);
		int[] rez=new int[arg.length];
		
		for(int i=0; i<arg.length; i++)
		{
			int a=26- arg[i] ;//CUtil.CoModule(arg[i],26);
			if(a == -1)
				return null;
			rez[i]=a;
		}
		
		return CUtil.NumbersToText(rez);
	}
	

	
}
